package com.cskaoyan.order.service.impl;

import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;


@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;



    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    // 增加事务
    @Transactional
    public String createOrder(CreateOrderRequest request) {
        //创建pipeline对象
        // 这里采用工厂方式创建，会复杂一些
        TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

        //启动pipeline
        invoker.start(); //启动流程（pipeline来处理）

        //获取处理结果
        AbsTransHandlerContext context = invoker.getContext();

        //从Context中获取订单Id
        String orderId = context.getOrderId();
        return orderId;
    }

    @Override
    public void cancelOrder(String orderId) {

        Order order = new Order();
        order.setStatus(OrderConstants.CANCEL_ORDER_STATUS);
        Example orderExample = new Example(Order.class);
        orderExample.createCriteria().andEqualTo("orderId", orderId);
        orderMapper.updateByExampleSelective(order, orderExample);

        orderItemMapper.updateStockStatus(OrderConstants.STOCK_FREE, orderId);

        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(orderId);
        for (OrderItem orderItem : orderItems) {
            Stock targetStock = stockMapper.selectStock(orderItem.getItemId());
            targetStock.setStockCount(orderItem.getNum().longValue());
            targetStock.setLockCount(-orderItem.getNum());
            stockMapper.updateStock(targetStock);
        }
        // for (int i = 0; i < orderItems.size(); i++) {
        //     Stock targetStock = stockMapper.selectStock(orderItems.get(i).getItemId());
        //     targetStock.setStockCount(targetStock.getStockCount() + orderItems.get(i).getNum());
        //     targetStock.setLockCount(targetStock.getLockCount() - orderItems.get().getNum());
        //     stockMapper.updateByPrimaryKeySelective(targetStock);
        // }

    }

    /**
     * 删除订单的实现
     * todo :
     * 库存表 ,两种情况 : 已付款 不做修改
     * 未付款 根据用户下单商品的数量回滚库存
     * 订单商品表 : 未付款 : 删除订单商品记录
     * 已付款 : 留存订单商品记录
     * 订单表 : 删除一条订单记录
     *
     * @param orderId 订单id
     * @return void
     * @author 小焦
     * @since 2022/10/26 上午 09:35
     */
    @Transactional
    @Override
    public boolean deleteOrder(String orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        //若订单状态为以下状态 ,说明订单已完成,可以删除
        if (order.getStatus() == 0 || order.getStatus() == 5 || order.getStatus() == 5 || order.getStatus() == 6 || order.getStatus() == 7) {
            Order updateOrder = new Order();
            updateOrder.setStatus(8);
            Example example = new Example(Order.class);
            example.createCriteria().andEqualTo("orderId", orderId);
            // 修改订单状态为 8
            orderMapper.updateByExampleSelective(updateOrder, example);
            // 如果订单状态为 0, 则回滚库存
            if (order.getStatus() == 0) {
                Example orderItemExample = new Example(OrderItem.class);
                orderItemExample.createCriteria().andEqualTo("orderId", orderId);
                // 释放库存
                orderItemMapper.updateStockStatus(2, orderId);
                List<OrderItem> orderItems = orderItemMapper.selectByExample(orderItemExample);
                for (OrderItem orderItem : orderItems) {
                    try {
                        rollbaStockNum(orderItem);
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
            return true;
        } else {
            //订单未完成不能删除
            return false;
        }

    }

    private void rollbaStockNum(OrderItem orderItem) {
        Integer num = orderItem.getNum();
        Long itemId = orderItem.getItemId();
        // 通过商品id拿到商品库存数据
//        Stock productStock = stockMapper.selectByPrimaryKey(itemId);
        // 修改库存中的商品数据
        Stock stock = new Stock();
        stock.setItemId(itemId);
        stock.setLockCount(-num);
        stock.setStockCount((long) num);
        Example stockExample = new Example(Stock.class);
        stockExample.createCriteria().andEqualTo("itemId");
        stockMapper.updateStock(stock);
    }

    @Override
    public void updateOrder(Integer status, String orderId) {
    }

}
